//
//  MTRecentlyViewController.swift
//  MT
//
//  Created by ooops on 2020/6/1.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import JXCategoryView
import JXPagingView
import MTCategory
import YPNavigationBarTransition
import JXSegmentedView
import RxSwift
import RxCocoa
import Result

extension MTRecentlyViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    //MARK: UICollectionViewDataSource
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // TODO:- Required Method
        return models.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MTMTRecentlyCell.reuseIdentity(), for: indexPath) as! MTMTRecentlyCell
        configureCell(cell: cell, forItemAt: indexPath)
        // TODO:- Required Method
        let model = self.models[indexPath.item]
        cell.model = model
        return cell
    }
    
    func configureCell(cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
    }
    
//    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//        let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: MTMTRecentlyCell.reuseIdentity(), for: indexPath)
//        return view
//    }
    
    //MARK: UICollectionViewDelegate
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.models[indexPath.item]
        let vc = MTLatestViewController(model: model)
        self.navigationVC?.pushViewController(vc, animated: true)
    }
    
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
    
}

extension MTRecentlyViewController {
    /// 数据请求
    private func dataRequest(isAppendingDatas: Bool = false, completion: (() -> Swift.Void)? = nil) {
        provider.rx.requestResult(requestTarget).subscribe(onNext: { [weak self] (result: Result<HomeListDetailReponseModel, AnyError>, isCache: Bool) in
            guard let weakSelf = self else { return }
            weakSelf.collectionView.mj_header?.endRefreshing()
            weakSelf.collectionView.mj_footer?.endRefreshing()
            
            switch result {
            case .success(let model):
                
                weakSelf.currentPage += 1
                if let result = model.result {
                    if isAppendingDatas {
                        weakSelf.models += result
                    } else {
                        //weakSelf.collectionView.player.stopCurrentPlayingCell()
                        weakSelf.models = result
                        //weakSelf.collectionView.playVideo(at: IndexPath(row: 0, section: 0), scrollToTop: false)
                    }
                    if model.page?.total == weakSelf.models.count {
                        weakSelf.currentPage -= 1
                        weakSelf.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                    }
                } else {
                    weakSelf.currentPage -= 1
                }
                break
                
            case .failure(_):
                break
                
            }
            
            if let completion = completion {
                completion()
            }
            
        }).disposed(by: globalDisposedBag)
    }
    
}

class MTRecentlyViewController: BaseViewController {
    
    /// 列表展示性别 - 默认为不限
    var displayGenderType: LocalGenderModel.GenderType = .unknown
    /// 当前页数
    var currentPage: Int = 1
    /// 请求类型
    private var requestTarget: HomeApi {
        switch dataDisplayType {
        case .hottest:
            return displayGenderType == .unknown ? .hotListWithoutGender(curPage: currentPage) : .hotList(curPage: currentPage, sex: displayGenderType.requestType)
        case .latest:
            return displayGenderType == .unknown ? .latestListWithoutGender(curPage: currentPage) : .latestList(curPage: currentPage, sex: displayGenderType.requestType)
        }
    }
    /// 列表展示模型
    var models: [HomeListDetailModel] = [] {
        didSet {
            collectionView.reloadData()
        }
    }
    
    /// 重新加载所有数据
    public func reloadAllData(completion: (() -> Swift.Void)? = nil) {
        currentPage = 1
        //models = []
        dataRequest(completion: completion)
    }
    
    /// 展示数据类型
    var dataDisplayType: NewDataDisplayType = .latest {
        didSet {
            //tableView.type = dataDisplayType.rawValue
            reloadAllData()
        }
    }
    
    @objc public func loadMore() {
        dataRequest(isAppendingDatas: true)
    }
    
    @objc public func loadFirst() {
        currentPage = 1
        reloadAllData()
    }
    
    public var listViewDidScrollCallback: ((UIScrollView) -> ())?
    
    /// MTProvider
    private lazy var provider: MTProvider<HomeApi> = {
        return MTProvider<HomeApi>(plugins: [])
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(navBgView)
        view.addSubview(collectionView)
        navBgView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(StatusBarHeight + NavigationBarHeight)
        }
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(navBgView.snp.bottom)
            make.left.right.equalToSuperview()
            //make.bottom.equalToSuperview().offset(-TabBarHeight)
            make.height.equalTo(ScreenHeight - TabBarHeight - StatusBarHeight - NavigationBarHeight)
        }
        
        reloadAllData()
    }
    
    lazy var navBgView: UIView = {
        let v = UIView()
        v.backgroundColor = .black
        return v
    }()
    
    lazy var collectionView: UICollectionView = {
        /// 设置大小
        //let inset: CGFloat = 15.0
        let itemWidth = (ScreenWidth - 4) / 2
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth * 250 / 186)
        flowLayout.minimumLineSpacing = 3
        flowLayout.minimumInteritemSpacing = 3
        let cv = UICollectionView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: MiTuGiftView.collectionViewHeight), collectionViewLayout: flowLayout)
        cv.backgroundColor = UIColor.common.x161616
//        cv.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: ScreenBottomExtraOffset + 15, right: 0)
        cv.showsVerticalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
        //        cv.isPagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        /// 注册 Cell
        cv.register(MTMTRecentlyCell.self, forCellWithReuseIdentifier: MTMTRecentlyCell.reuseIdentity())
        cv.emptySetView = ViewFactory.emptySetView { [weak self] in
            guard let weakself = self else { return }
            weakself.dataRequest(isAppendingDatas: false, completion: nil)
        }
        cv.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMore))
        cv.mj_header = ViewFactory.normalHeader(target: self, selector: #selector(loadFirst))
        return cv
    }()
    
    public func setGenderType(_ genderType: LocalGenderModel.GenderType, isCurrentPagingController: Bool) {
        displayGenderType = genderType
        reloadAllData {
            
        }
    }

}

extension MTRecentlyViewController: JXSegmentedListContainerViewListDelegate {
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        listViewDidScrollCallback = callback
    }


    func listView() -> UIView {
        return self.view
    }

    func listScrollView() -> UIScrollView {
        return self.collectionView
    }
}
